import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, MAGIC_NUMBERS, column, toSelectDataSource } from './stores/definitions';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import { useStore } from '@/hooks';
import { Button, Dialog, Message } from '@alifd/next';
import TaskInfoDrawer from './components/TaskInfoDrawer';
import OrderInfoDrawer from './components/OrderInfoDrawer';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import SendCar from './components/SendCarDrawer';
import AlterationDrawer from './components/AlterationDrawer';
import CancelCarDrawer from './components/CancelCarDialog';
import FinishTaskDialog from './components/FinishTaskDialog';
import moment from 'moment';


const tableId = uniqueId('tauTable');

function parseRegion(s) {
  if (!s?.length) return {};
  return { main: s[0]?.itemId, minor: s[1]?.id };
}

function RsTask() {
  const { rsTaskStore: store } = useStore();
  const { TASK_STATE, DRIVER_STATE } = MAGIC_NUMBERS;
  const curRef = useRef();
  const [modal, setModal] = useState([]);


  useEffect(() => {
    (async () => {
      store._mainArgs.search = {
        taskType: '2',
      };
      store._mainArgs.query();
    })();
  }, []);

  const handleOnSearch = (params) => {
    const { orderDate, startStations: d1, endStations: d2, ...searchArgs } = params?.values;
    const { startStations, endStations } = params?.valueObjects;
    const [from, to] = orderDate || [];
    const { main: startMainArea, minor: startMinorAreas } = parseRegion(startStations?.selectedPath || {});
    const { main: endMainArea, minor: endMinorAreas } = parseRegion(endStations?.selectedPath || {});
    store._mainArgs.search = {
      taskType: '2',
      from,
      to,
      startMainArea,
      startMinorAreas,
      endMainArea,
      endMinorAreas,
      ...searchArgs,
    };
  };

  const handleTableAction = (info, action) => {
    switch (action) {
      case 'viewTask':
        handleOpenTask(info);
        break;
      case 'viewOrder':
        handleOpenOrder(info);
        break;
      case 'edit':
        handleOpenEdit(info);
        break;
      case 'manual':
        handleSendCar(info);
        break;
      case 'alteration':
        handleAlteration(info);
        break;
      case 'cancelSendCar':
        handleCancelCar(info);
        break;
      case 'finishTask':
      case 'pickUpPassenger':
      case 'pickedPassenger':
      case 'arrive':
        handleFinishTask(info, action);
        break;
      default:
        break;
    }
  };

  const handleOpenTask = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['viewTask']);
  };

  const handleOpenOrder = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['viewOrder']);
  };

  const handleOpenEdit = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['edit']);
  };

  const handleSendCar = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['manual']);
  };

  const handleAlteration = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['alteration']);
  };

  const handleCancelCar = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['cancelSendCar']);
  };

  const handleFinishTask = (taskInfo, action) => {
    curRef.current = taskInfo;
    setModal(['changeTaskState', action]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      Dialog.confirm({
        content: t`确定要变更吗?`,
        onOk: async () => {
          try {
            const { arCarrierCompanyId, arCarrierCompanyName, arCarrierCompanyPrice, id } = result;
            const params = {
              taskId: id,
              carrierCompany: arCarrierCompanyId,
              carrierCompanyName: arCarrierCompanyName,
              carrierCompanyPrice: arCarrierCompanyPrice,
            };
            await store.update(params);
            Message.success({ content: t`变更成功` });
          } catch (e) {
            Message.error({ content: t`变更失败`, duration: 7000 });
            throw e;
          }
          setModal([]);
        },
      });
    }
  };

  // 价格设置提交
  const handleSetPrice = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.updatePrice(result);
        Message.success({ content: t`设置价格成功` });
      } catch (e) {
        Message.error({ content: t`设置价格失败!${e.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'startStations',
            type: 'rs-station',
            props: { placeholder: t`始发站点`, changeOnSelect: true, style: { minWidth: '160px' } },
          },
          {
            name: 'endStations',
            type: 'rs-station',
            props: { placeholder: t`结束站点`, changeOnSelect: true, style: { minWidth: '160px' } },
          },
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始日期`, t`结束日期`],
            },
          },
          {
            name: 'states',
            type: 'select',
            props: {
              placeholder: t`任务状态`,
              dataSource: toSelectDataSource(ENUMS.states),
              mode: 'multiple',
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store._mainArgs.pg.page}
          pageSize={store._mainArgs.pg.size}
          total={store._mainArgs.total}
          sort={store._mainArgs.tableSort}
          onFetch={(pg) => { store._mainArgs.pg = pg; }}
          loading={store._mainArgs.loading}
          dataSource={toJS(store._mainArgs.dataSource)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
            {
              title: t`任务编号`,
              width: 140,
              cell: (v, _, row) => {
                return (
                  <Button
                    key={row.id}
                    type="primary"
                    text
                    onClick={() => handleTableAction(row, 'viewTask')}
                  >
                    {row.id}
                  </Button>
                );
              },
            },
            column('startArea', { width: 120 }),
            column('endArea', { width: 120 }),
            column('carrierCompanyName', { width: 60 }),
            column('driverSettlement', { width: 58 }),
            column('showPrice', { width: 120 }),
            column('state', { width: 58 }),
            column('departureTime', { width: 90 }),
          ].concat(global.isAdmin ? [
            column('totalPrice', { width: 58 }),
            {
              title: t`相关订单/票数`,
              width: 180,
              cell: (v, _, row) => {
                const { orderIds = [], tickets } = row;
                return (
                  <>
                    {orderIds.map((id, idx) => {
                      const idGroup = tickets.reduce((acc, ticket) => {
                        const { orderId } = ticket;
                        let total = acc;
                        if (orderId === id) {
                          total += 1;
                        }
                        return total;
                      }, 0);
                      return (
                        <Button
                          key={`${id}-${idx}`}
                          type="primary"
                          text
                          onClick={() => {
                            const info = {
                              orderId: id,
                              taskInfo: row,
                            };
                            handleTableAction(info, 'viewOrder');
                          }}
                        >
                          {`${id} / ${idGroup}`}
                        </Button>
                      );
                    })}
                  </>
                );
              },
            }] : [])
            .concat([{
              title: t`操作`,
              width: 118,
              cell: (__, ___, record) => {
                const { grouped = false, state, orderBaseModel, driverInfo } = record;
                const canGrouped = grouped;

                const { predictTime, predictBeginDate } = orderBaseModel || {};
                const baseTime = moment(predictBeginDate).add(predictTime, 'hour');
                const curDriverInfo = store.getDriverInfo(driverInfo) || {};
                const { state: driverState } = curDriverInfo;
                const now = moment();
                let isManualFinish = false;

                if (moment(now).isAfter(moment(baseTime))) {
                  isManualFinish = true;
                }

                const funcMenu = [
                  {
                    title: '编辑',
                    onClick: () => handleTableAction(record, 'edit'),
                    show: global.isAdmin,
                  },
                  {
                    title: '派车',
                    onClick: () => handleTableAction(record, 'manual'),
                    show: canGrouped && state === TASK_STATE.WAITING,
                  },
                  {
                    title: '任务变更',
                    onClick: () => handleTableAction(record, 'alteration'),
                    show: canGrouped && (state === TASK_STATE.WAITING) && global.isAdmin,
                  },
                  {
                    title: '取消派车',
                    onClick: () => handleTableAction(record, 'cancelSendCar'),
                    show: state === TASK_STATE.START,
                  },
                  {
                    title: '干预完成',
                    onClick: () => handleTableAction(record, 'finishTask'),
                    show: state === TASK_STATE.START && isManualFinish,
                  },
                  {
                    title: '去接乘客',
                    onClick: () => handleTableAction(record, 'pickUpPassenger'),
                    show: !isManualFinish && driverState === DRIVER_STATE.SEND_CAR,
                  },
                  {
                    title: '接到乘客',
                    onClick: () => handleTableAction(record, 'pickedPassenger'),
                    show: !isManualFinish && driverState === DRIVER_STATE.GOING,
                  },
                  {
                    title: '到达目的地',
                    onClick: () => handleTableAction(record, 'arrive'),
                    show: !isManualFinish && driverState === DRIVER_STATE.PICKED,
                  },
                ];
                return (
                  <MoreFuncDropDown
                    dropdownItems={funcMenu}
                    maxShow={1}
                  />
                );
              },
            }])
          }
        />
      </div>
      <TaskInfoDrawer
        visible={modal[0] === 'viewTask' || modal[0] === 'edit'}
        task={curRef.current}
        modal={modal}
        handleUpdate={handleUpdate}
        onClose={() => {
          setModal([]);
        }}
      />
      <OrderInfoDrawer
        visible={modal[0] === 'viewOrder'}
        orderId={curRef.current?.orderId}
        task={curRef.current?.taskInfo}
        onClose={() => {
          setModal([]);
        }}
      />
      <SendCar
        visible={modal[0] === 'manual'}
        task={curRef.current}
        onClose={() => {
          setModal([]);
        }}
        onSubmit={handleSetPrice}
      />
      <AlterationDrawer
        visible={modal[0] === 'alteration'}
        task={curRef.current}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        modal={modal}
        onCancel={() => setModal([])}
        onSubmit={handleUpdate}
      />
      <CancelCarDrawer
        visible={modal[0] === 'cancelSendCar'}
        task={curRef.current}
        onClose={() => {
          setModal([]);
        }}
      />
      <FinishTaskDialog
        visible={modal[0] === 'changeTaskState'}
        task={curRef.current}
        action={modal[1]}
        onClose={async () => {
          setModal([]);
          await store._mainArgs.query();
        }}
      />
    </TauPage>
  );
}

export default observer(RsTask);
